package com.ddm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ddm.constant.MessageConstant;
import com.ddm.dto.*;
import com.ddm.dto.page.LevelPageQueryDTO;
import com.ddm.entity.*;
import com.ddm.exception.DataErrorException;
import com.ddm.mapper.Level1Mapper;
import com.ddm.mapper.Level2Mapper;
import com.ddm.mapper.Level3Mapper;
import com.ddm.mapper.Level4Mapper;
import com.ddm.result.PageResult;
import com.ddm.service.*;
import com.ddm.vo.LevelVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static com.ddm.constant.LevelConstant.LAST_INDEX;

/**
 * @author 丁丁猫
 * @version 1.0
 */
@Service
public class LevelServiceImpl implements LevelService {
    @Autowired
    private CommonService commonService;

    @Autowired
    private Level1Mapper level1Mapper;

    @Autowired
    private Level2Mapper level2Mapper;

    @Autowired
    private Level3Mapper level3Mapper;

    @Autowired
    private Level4Mapper level4Mapper;


    /**
     * 检测级数是否存在
     *
     * @param levelDTO
     * @return
     */
    @Override
    public boolean checkLevel(LevelDTO levelDTO) {
        if (levelDTO.getLevel() == 1) {
            return (level1Mapper.selectById(levelDTO.getId()) != null);
        }
        if (levelDTO.getLevel() == 2) {
            return (level2Mapper.selectById(levelDTO.getId()) != null);
        }
        if (levelDTO.getLevel() == 3) {
            return (level3Mapper.selectById(levelDTO.getId()) != null);
        }
        if (levelDTO.getLevel() == 4) {
            return (level4Mapper.selectById(levelDTO.getId()) != null);
        }
        return false;
    }

    /**
     * 新增指标
     *
     * @param levelDTO
     */
//    @Override
//    public void save(LevelDTO levelDTO) {
//        String image = "";
//        // 图片列表转字符串
//        if (CollectionUtils.isNotEmpty(levelDTO.getImageList())) {
//            image = commonService.convertListToString(levelDTO.getImageList());
//        }
//        if (levelDTO.getLevel() == 1) {
//            Level1 level1 = new Level1();
//            BeanUtils.copyProperties(levelDTO, level1);
//            level1.setImage(image);
//            level1Mapper.insert(level1);
//        }
//        if (levelDTO.getLevel() == 2) {
//            Level2 level2 = new Level2();
//            BeanUtils.copyProperties(levelDTO, level2);
//            level2.setImage(image);
//            level2Mapper.insert(level2);
//        }
//        if (levelDTO.getLevel() == 3) {
//            Level3 level3 = new Level3();
//            BeanUtils.copyProperties(levelDTO, level3);
//            level3.setImage(image);
//            level3Mapper.insert(level3);
//        }
//        if (levelDTO.getLevel() == 4) {
//            Level4 level4 = new Level4();
//            BeanUtils.copyProperties(levelDTO, level4);
//            level4.setImage(image);
//            level4Mapper.insert(level4);
//        }
//    }
    @Override
    public Long saveV(LevelDTO levelDTO) {
        // 先判断是否已存在相同的 numId 和 standard_id
        if (levelDTO.getLevel() == 1) {
            Level1 exist = level1Mapper.selectOne(new QueryWrapper<Level1>()
                    .eq("num_id", levelDTO.getNumId())
                    .eq("standard_id", levelDTO.getStandardId()));
            if (exist != null) {
                return null;
            }
        } else if (levelDTO.getLevel() == 2) {
            Level2 exist = level2Mapper.selectOne(new QueryWrapper<Level2>()
                    .eq("num_id", levelDTO.getNumId())
                    .eq("standard_id", levelDTO.getStandardId()));
            if (exist != null) {
                return null;
            }
        } else if (levelDTO.getLevel() == 3) {
            Level3 exist = level3Mapper.selectOne(new QueryWrapper<Level3>()
                    .eq("num_id", levelDTO.getNumId())
                    .eq("standard_id", levelDTO.getStandardId()));
            if (exist != null) {
                return null;
            }
        } else if (levelDTO.getLevel() == 4) {
            Level4 exist = level4Mapper.selectOne(new QueryWrapper<Level4>()
                    .eq("num_id", levelDTO.getNumId())
                    .eq("standard_id", levelDTO.getStandardId()));
            if (exist != null) {
                return null;
            }
        }
        Long id = null;
        String image = "";
        // 图片列表转字符串
        if (CollectionUtils.isNotEmpty(levelDTO.getImageList())) {
            image = commonService.convertListToString(levelDTO.getImageList());
        }
        // 保存当前指标
        if (levelDTO.getLevel() == 1) {
            Level1 level1 = new Level1();
            BeanUtils.copyProperties(levelDTO, level1);
            level1.setImage(image);
            level1Mapper.insert(level1);
            id = level1.getId();
        }
        if (levelDTO.getLevel() == 2) {
            Level2 level2 = new Level2();
            BeanUtils.copyProperties(levelDTO, level2);
            level2.setImage(image);
            level2Mapper.insert(level2);
            id = level2.getId();
        }
        if (levelDTO.getLevel() == 3) {
            Level3 level3 = new Level3();
            BeanUtils.copyProperties(levelDTO, level3);
            level3.setImage(image);
            level3Mapper.insert(level3);
            id = level3.getId();
        }
        if (levelDTO.getLevel() == 4) {
            Level4 level4 = new Level4();
            BeanUtils.copyProperties(levelDTO, level4);
            level4.setImage(image);
            level4Mapper.insert(level4);
            id = level4.getId();
        }

        // 如果当前指标不是顶级，则更新其父级指标的 ifNextLevel 为 1
        if (levelDTO.getLevel() > 1) {
            // 父级指标的numId为当前numId去掉最后一个"."及后面的数字
            String numId = levelDTO.getNumId();
            int lastDotIndex = numId.lastIndexOf(".");
            if (lastDotIndex > 0) {
                String parentNumId = numId.substring(0, lastDotIndex);
                // 根据当前级别，父级的级别 = 当前级别 - 1，选择对应的Mapper进行更新
                if (levelDTO.getLevel() == 2) {
                    // 父级在level1表中
                    Level1 parent = level1Mapper.selectOne(new QueryWrapper<Level1>()
                            .eq("standard_id", levelDTO.getStandardId())
                            .eq("num_id", parentNumId));
                    if (parent != null && parent.getIfNextLevel() != 1) {
                        parent.setIfNextLevel(1L);
                        level1Mapper.updateById(parent);
                    }
                } else if (levelDTO.getLevel() == 3) {
                    // 父级在level2表中
                    Level2 parent = level2Mapper.selectOne(new QueryWrapper<Level2>()
                            .eq("standard_id", levelDTO.getStandardId())
                            .eq("num_id", parentNumId));
                    if (parent != null && parent.getIfNextLevel() != 1) {
                        parent.setIfNextLevel(1L);
                        level2Mapper.updateById(parent);
                    }
                } else if (levelDTO.getLevel() == 4) {
                    // 父级在level3表中
                    Level3 parent = level3Mapper.selectOne(new QueryWrapper<Level3>()
                            .eq("standard_id", levelDTO.getStandardId())
                            .eq("num_id", parentNumId));
                    if (parent != null && parent.getIfNextLevel() != 1) {
                        parent.setIfNextLevel(1L);
                        level3Mapper.updateById(parent);
                    }
                }
            }
        }
        return id;
    }


    /**
     * 根据id修改指标
     *
     * @param levelDTO
     */
    @Override
    public void updateById(LevelDTO levelDTO) {
        String image = "";
        // 图片列表转字符串
        if (CollectionUtils.isNotEmpty(levelDTO.getImageList())) {
            image = commonService.convertListToString(levelDTO.getImageList());
        }
        // 判断指标是否存在
        if (checkLevel(levelDTO)) {
            if (levelDTO.getLevel() == 1) {
                Level1 level1 = new Level1();
                BeanUtils.copyProperties(levelDTO, level1);
                level1.setImage(image);
                level1Mapper.updateById(level1);
            }
            if (levelDTO.getLevel() == 2) {
                Level2 level2 = new Level2();
                BeanUtils.copyProperties(levelDTO, level2);
                level2.setImage(image);
                level2Mapper.updateById(level2);
            }
            if (levelDTO.getLevel() == 3) {
                Level3 level3 = new Level3();
                BeanUtils.copyProperties(levelDTO, level3);
                level3.setImage(image);
                level3Mapper.updateById(level3);
            }
            if (levelDTO.getLevel() == 4) {
                Level4 level4 = new Level4();
                BeanUtils.copyProperties(levelDTO, level4);
                level4.setImage(image);
                level4Mapper.updateById(level4);
            }
        } else {
            throw new DataErrorException(MessageConstant.NULL_RECORD);
        }
    }

    /**
     * 根据关键词分页查询指标
     * @param levelPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryByKeyWord(LevelPageQueryDTO levelPageQueryDTO) {
        if (levelPageQueryDTO.getLevel() == 1) {
            IPage<Level1> page = new Page(levelPageQueryDTO.getPage(), levelPageQueryDTO.getPageSize());
            LambdaQueryWrapper<Level1> lqw = new LambdaQueryWrapper();
            //按照numId排序【升序】
            lqw.like(StringUtils.isNotEmpty(levelPageQueryDTO.getKey()), Level1::getName, levelPageQueryDTO.getKey())
                    .orderByAsc(Level1::getNumId);
            level1Mapper.selectPage(page, lqw);
            long total = page.getTotal();
            List<Level1> records = page.getRecords();
            records.sort(Comparator.comparing(level1 -> Integer.parseInt(commonService.extractNumId(level1.getNumId(),LAST_INDEX))));
            //设置数据
            PageResult pageResult = new PageResult(total, records);
            return pageResult;
        }
        if (levelPageQueryDTO.getLevel() == 2) {
            IPage<Level2> page = new Page(levelPageQueryDTO.getPage(), levelPageQueryDTO.getPageSize());
            LambdaQueryWrapper<Level2> lqw = new LambdaQueryWrapper();
            //按照numId排序【升序】
            lqw.like(StringUtils.isNotEmpty(levelPageQueryDTO.getKey()), Level2::getName, levelPageQueryDTO.getKey())
                    .orderByAsc(Level2::getNumId);
            level2Mapper.selectPage(page, lqw);
            long total = page.getTotal();
            List<Level2> records = page.getRecords();
            records.sort(Comparator.comparing(level2 -> Integer.parseInt(commonService.extractNumId(level2.getNumId(),LAST_INDEX))));
            //设置数据
            PageResult pageResult = new PageResult(total, records);
            return pageResult;
        }
        if (levelPageQueryDTO.getLevel() == 3) {
            IPage<Level3> page = new Page(levelPageQueryDTO.getPage(), levelPageQueryDTO.getPageSize());
            LambdaQueryWrapper<Level3> lqw = new LambdaQueryWrapper();
            //按照numId排序【升序】
            lqw.like(StringUtils.isNotEmpty(levelPageQueryDTO.getKey()), Level3::getName, levelPageQueryDTO.getKey())
                    .orderByAsc(Level3::getNumId);
            level3Mapper.selectPage(page, lqw);
            long total = page.getTotal();
            List<Level3> records = page.getRecords();
            records.sort(Comparator.comparing(level3 -> Integer.parseInt(commonService.extractNumId(level3.getNumId(),LAST_INDEX))));
            //设置数据
            PageResult pageResult = new PageResult(total, records);
            return pageResult;
        }
        if (levelPageQueryDTO.getLevel() == 4) {
            IPage<Level4> page = new Page(levelPageQueryDTO.getPage(), levelPageQueryDTO.getPageSize());
            LambdaQueryWrapper<Level4> lqw = new LambdaQueryWrapper();
            //按照numId排序【升序】
            lqw.like(StringUtils.isNotEmpty(levelPageQueryDTO.getKey()), Level4::getName, levelPageQueryDTO.getKey())
                    .orderByAsc(Level4::getNumId);
            level4Mapper.selectPage(page, lqw);
            long total = page.getTotal();
            List<Level4> records = page.getRecords();
            records.sort(Comparator.comparing(level4 -> Integer.parseInt(commonService.extractNumId(level4.getNumId(),LAST_INDEX))));
            //设置数据
            PageResult pageResult = new PageResult(total, records);
            return pageResult;
        }
        return null;
    }

    /**
     * 根据id和level获取指标
     * @param id
     * @param level
     * @return
     */
    @Override
    public LevelVO getById(Long id,Long level) {
        LevelVO levelVO = new LevelVO();
        if (level == 1) {
            Level1 level1 = level1Mapper.selectById(id);
            if (level1 != null) {
                BeanUtils.copyProperties(level1, levelVO);
                return levelVO;
            }
        }
        if (level == 2) {
            Level2 level2 = level2Mapper.selectById(id);
            if (level2 != null) {
                BeanUtils.copyProperties(level2, levelVO);
                return levelVO;
            }
        }
        if (level == 3) {
            Level3 level3 = level3Mapper.selectById(id);
            if (level3 != null) {
                BeanUtils.copyProperties(level3, levelVO);
                return levelVO;
            }
        }
        if (level == 4) {
            Level4 level4 = level4Mapper.selectById(id);
            if (level4 != null) {
                BeanUtils.copyProperties(level4, levelVO);
                return levelVO;
            }
        }
        return null;
    }

    /**
     * 删除指标
     * @param id
     */
    @Override
    public void removeById(Long id,Long level) {
        if (level == 1) {
            level1Mapper.deleteById(id);
        }
        if (level == 2) {
            level2Mapper.deleteById(id);
        }
        if (level == 3) {
            level3Mapper.deleteById(id);
        }
        if (level == 4) {
            level4Mapper.deleteById(id);
        }
    }

    /**
     * 根据standardId批量删除指标
     * @param standardId
    */
    @Override
    public void removeByStandardId(Long standardId) {
        LambdaQueryWrapper<Level1> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Level1::getStandardId, standardId);
        level1Mapper.delete(lqw1);
        LambdaQueryWrapper<Level2> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(Level2::getStandardId, standardId);
        level2Mapper.delete(lqw2);
        LambdaQueryWrapper<Level3> lqw3 = new LambdaQueryWrapper<>();
        lqw3.eq(Level3::getStandardId, standardId);
        level3Mapper.delete(lqw3);
        LambdaQueryWrapper<Level4> lqw4 = new LambdaQueryWrapper<>();
        lqw4.eq(Level4::getStandardId, standardId);
        level4Mapper.delete(lqw4);
    }

    /**
     * 保存所有指标
     * @param allLevelDTO
     */
    @Override
    public void saveAll(AllLevelDTO allLevelDTO) {
        List<Level1DTO> level1List = allLevelDTO.getLevel1DTO();
        for (Level1DTO level1DTO : level1List) {
            Level1 level1 = new Level1();
            //拷贝数据
            BeanUtils.copyProperties(level1DTO, level1);
            // 图片列表转字符串
            if (CollectionUtils.isNotEmpty(level1DTO.getImageList())) {
                String image = commonService.convertListToString(level1DTO.getImageList());
                level1.setImage(image);
            }
            level1.setStandardId(allLevelDTO.getStandardId());
            level1.setLevel(1L);
            level1.setIfNextLevel(0L);
            // 递归保存 Level2 数据
            if (CollectionUtils.isNotEmpty(level1DTO.getLevel2DTO())) {
                //存在下一级
                level1.setIfNextLevel(1L);
                for (Level2DTO level2DTO : level1DTO.getLevel2DTO()) {
                    Level2 level2 = new Level2();
                    //拷贝数据
                    BeanUtils.copyProperties(level2DTO, level2);
                    // 图片列表转字符串
                    if (CollectionUtils.isNotEmpty(level2DTO.getImageList())) {
                        String image = commonService.convertListToString(level2DTO.getImageList());
                        level2.setImage(image);
                    }
                    level2.setStandardId(allLevelDTO.getStandardId());
                    level2.setLevel(2L);
                    level2.setIfNextLevel(0L);
                    // 递归保存 Level3 数据
                    if (CollectionUtils.isNotEmpty(level2DTO.getLevel3DTO())) {
                        //存在下一级
                        level2.setIfNextLevel(1L);
                        for (Level3DTO level3DTO : level2DTO.getLevel3DTO()) {
                            Level3 level3 = new Level3();
                            //拷贝数据
                            BeanUtils.copyProperties(level3DTO, level3);
                            // 图片列表转字符串
                            if (CollectionUtils.isNotEmpty(level3DTO.getImageList())) {
                                String image = commonService.convertListToString(level3DTO.getImageList());
                                level3.setImage(image);
                            }
                            level3.setStandardId(allLevelDTO.getStandardId());
                            level3.setLevel(3L);
                            level3.setIfNextLevel(0L);
                            // 递归保存 Level4 数据
                            if (CollectionUtils.isNotEmpty(level3DTO.getLevel4DTO())) {
                                //存在下一级
                                level3.setIfNextLevel(1L);
                                for (Level4DTO level4DTO : level3DTO.getLevel4DTO()) {
                                    Level4 level4 = new Level4();
                                    //拷贝数据
                                    BeanUtils.copyProperties(level4DTO, level4);
                                    // 图片列表转字符串
                                    if (CollectionUtils.isNotEmpty(level4DTO.getImageList())) {
                                        String image = commonService.convertListToString(level4DTO.getImageList());
                                        level4.setImage(image);
                                    }
                                    level4.setStandardId(allLevelDTO.getStandardId());
                                    level4.setLevel(4L);
                                    level4.setIfNextLevel(0L);
                                    //保存 Level4 数据
                                    level4Mapper.insert(level4);
                                }
                            }
                            //保存 Level3 数据
                            level3Mapper.insert(level3);
                        }
                    }
                    //保存 Level2 数据
                    level2Mapper.insert(level2);
                }
            }
            // 保存 Level1 数据
            level1Mapper.insert(level1);
        }
    }

    /**
     * 新增指标Plus
     * @param standardId
     */
    @Override
    @Transactional
    public void savePlus(Long standardId) {
        // 1. 新增一级指标记录
        for (int i = 1; i <= 4; i++) {
            Level1 level1 = new Level1();
            level1.setStandardId(standardId);
            level1.setNumId(String.valueOf(i)); // "1", "2", "3", "4"
            level1.setLevel(1L);
            level1.setIfNextLevel(1L);
            level1.setName("未命名指标");
            // 根据需要设置其他字段，如 name、content、image 等
            level1Mapper.insert(level1);
        }

        // 2. 新增二级指标记录
        for (int i = 1; i <= 4; i++) {
            Level2 level2 = new Level2();
            level2.setStandardId(standardId);
            level2.setNumId(i + ".1"); // "1.1", "2.1", "3.1", "4.1"
            level2.setLevel(2L);
            level2.setIfNextLevel(1L);
            level2.setName("未命名指标");
            level2Mapper.insert(level2);
        }

        // 3. 新增三级指标记录
        for (int i = 1; i <= 4; i++) {
            Level3 level3 = new Level3();
            level3.setStandardId(standardId);
            level3.setNumId(i + ".1.1");
            level3.setLevel(3L);
            level3.setIfNextLevel(1L);
            level3.setName("未命名指标");
            level3Mapper.insert(level3);
        }

        // 4. 新增四级指标记录
        for (int i = 1; i <= 4; i++) {
            Level4 level4 = new Level4();
            level4.setStandardId(standardId);
            level4.setNumId(i + ".1.1.1");
            level4.setLevel(4L);
            level4.setIfNextLevel(0L);
            level4.setName("未命名指标");
            level4Mapper.insert(level4);
        }
    }

    /**
     * selectId查询指标
     * @param level
     * @param numId
     * @param standardId
     * @return
     */
    @Override
    public LevelVO getBySelectId(Long level, String numId, Long standardId) {
        LambdaQueryWrapper<Level1> lqw1 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Level2> lqw2 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Level3> lqw3 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Level4> lqw4 = new LambdaQueryWrapper<>();
        LevelVO levelVO = new LevelVO();
        if (level == 1) {
            Level1 level1 = level1Mapper.selectOne(lqw1.eq(Level1::getStandardId, standardId).eq(Level1::getNumId, numId));
            if (level1 != null) {
                BeanUtils.copyProperties(level1, levelVO);
                return levelVO;
            }
        }
        if (level == 2) {
            Level2 level2 = level2Mapper.selectOne(lqw2.eq(Level2::getStandardId, standardId).eq(Level2::getNumId, numId));
            if (level2 != null) {
                BeanUtils.copyProperties(level2, levelVO);
                return levelVO;
            }
        }
        if (level == 3) {
            Level3 level3 = level3Mapper.selectOne(lqw3.eq(Level3::getStandardId, standardId).eq(Level3::getNumId, numId));
            if (level3 != null) {
                BeanUtils.copyProperties(level3, levelVO);
                return levelVO;
            }
        }
        if (level == 4) {
            Level4 level4 = level4Mapper.selectOne(lqw4.eq(Level4::getStandardId, standardId).eq(Level4::getNumId, numId));
            if (level4 != null) {
                BeanUtils.copyProperties(level4, levelVO);
                return levelVO;
            }
        }
        throw new DataErrorException("未找到对应指标");
    }

    /**
     * 插入指标
     * @param dto
     */
    @Override
    public void saveI(LevelDTO dto) {
        Long level = dto.getLevel();
        String newNumId = dto.getNumId();
        Long stdId = dto.getStandardId();
        switch (level.intValue()) {
            case 1:
                shiftLevel1(stdId, newNumId);
                level1Mapper.insert(toLevel1(dto));
                break;
            case 2:
                shiftLevel2(stdId, newNumId);
                level2Mapper.insert(toLevel2(dto));
                updateParentIfNext(stdId,newNumId);
                break;
            case 3:
                shiftLevel3(stdId, newNumId);
                level3Mapper.insert(toLevel3(dto));
                updateParentIfNext(stdId,newNumId);
                break;
            case 4:
                shiftLevel4(stdId, newNumId);
                level4Mapper.insert(toLevel4(dto));
                updateParentIfNext(stdId,newNumId);
                break;
            default:
                throw new IllegalArgumentException("不支持的层级: " + level);
        }
        // 如果当前指标不是顶级，则更新其父级指标的 ifNextLevel 为 1
        if (dto.getLevel() > 1) {
            // 父级指标的numId为当前numId去掉最后一个"."及后面的数字
            String numId = dto.getNumId();
            int lastDotIndex = numId.lastIndexOf(".");
            if (lastDotIndex > 0) {
                String parentNumId = numId.substring(0, lastDotIndex);
                // 根据当前级别，父级的级别 = 当前级别 - 1，选择对应的Mapper进行更新
                if (dto.getLevel() == 2) {
                    // 父级在level1表中
                    Level1 parent = level1Mapper.selectOne(new QueryWrapper<Level1>()
                            .eq("standard_id", dto.getStandardId())
                            .eq("num_id", parentNumId));
                    if (parent != null && parent.getIfNextLevel() != 1) {
                        parent.setIfNextLevel(1L);
                        level1Mapper.updateById(parent);
                    }
                } else if (dto.getLevel() == 3) {
                    // 父级在level2表中
                    Level2 parent = level2Mapper.selectOne(new QueryWrapper<Level2>()
                            .eq("standard_id", dto.getStandardId())
                            .eq("num_id", parentNumId));
                    if (parent != null && parent.getIfNextLevel() != 1) {
                        parent.setIfNextLevel(1L);
                        level2Mapper.updateById(parent);
                    }
                } else if (dto.getLevel() == 4) {
                    // 父级在level3表中
                    Level3 parent = level3Mapper.selectOne(new QueryWrapper<Level3>()
                            .eq("standard_id", dto.getStandardId())
                            .eq("num_id", parentNumId));
                    if (parent != null && parent.getIfNextLevel() != 1) {
                        parent.setIfNextLevel(1L);
                        level3Mapper.updateById(parent);
                    }
                }
            }
        }
    }



    /**
     * 向后移动所有一级指标及其子孙节点的 numId
     */
    private void shiftLevel1(Long stdId, String newId) {
        // 同一级全局移动逻辑
        List<Level1> list = level1Mapper.selectList(new QueryWrapper<Level1>().eq("standard_id", stdId))
                .stream()
                .filter(l -> extractIndex(l.getNumId(), 1) >= extractIndex(newId, 1))
                .sorted(Comparator.comparing(l -> extractIndex(l.getNumId(), 1), Comparator.reverseOrder()))
                .collect(Collectors.toList());

        for (Level1 l : list) {
            String oldId = l.getNumId();
            int idx = extractIndex(oldId, 1);
            String newPrefix = String.valueOf(idx + 1);
            level1Mapper.update(null,
                    new UpdateWrapper<Level1>().set("num_id", newPrefix).eq("id", l.getId())
            );
            updateDescendants(stdId,oldId, newPrefix);
        }
    }

    /**
     * 向后移动同父级下的二级指标及其子孙节点的 numId
     */
    private void shiftLevel2(Long stdId, String newId) {
        String parent = getPrefix(newId, 1);
        int targetIdx = extractIndex(newId, 2);

        List<Level2> list = level2Mapper.selectList(new QueryWrapper<Level2>().eq("standard_id", stdId))
                .stream()
                // 仅处理与新节点同父级且序号 >= 插入位置的节点
                .filter(l -> getPrefix(l.getNumId(), 1).equals(parent)
                        && extractIndex(l.getNumId(), 2) >= targetIdx)
                .sorted(Comparator.comparing(l -> extractIndex(l.getNumId(), 2), Comparator.reverseOrder()))
                .collect(Collectors.toList());

        for (Level2 l : list) {
            String oldId = l.getNumId();
            int idx = extractIndex(oldId, 2);
            String newPrefix = parent + "." + (idx + 1);
            level2Mapper.update(null,
                    new UpdateWrapper<Level2>().set("num_id", newPrefix).eq("id", l.getId())
            );
            updateDescendants(stdId,oldId, newPrefix);
        }
    }

    /**
     * 向后移动同父级下的三级指标及其子孙节点的 numId
     */
    private void shiftLevel3(Long stdId, String newId) {
        String parent = getPrefix(newId, 2);
        int targetIdx = extractIndex(newId, 3);

        List<Level3> list = level3Mapper.selectList(new QueryWrapper<Level3>().eq("standard_id", stdId))
                .stream()
                .filter(l -> getPrefix(l.getNumId(), 2).equals(parent)
                        && extractIndex(l.getNumId(), 3) >= targetIdx)
                .sorted(Comparator.comparing(l -> extractIndex(l.getNumId(), 3), Comparator.reverseOrder()))
                .collect(Collectors.toList());

        for (Level3 l : list) {
            String oldId = l.getNumId();
            int idx = extractIndex(oldId, 3);
            String newPrefix = parent + "." + (idx + 1);
            level3Mapper.update(null,
                    new UpdateWrapper<Level3>().set("num_id", newPrefix).eq("id", l.getId())
            );
            updateDescendants(stdId,oldId, newPrefix);
        }
    }

    /**
     * 向后移动同父级下的四级指标的 numId（四级无子级）
     */
    private void shiftLevel4(Long stdId, String newId) {
        String parent = getPrefix(newId, 3);
        int targetIdx = extractIndex(newId, 4);

        List<Level4> list = level4Mapper.selectList(new QueryWrapper<Level4>().eq("standard_id", stdId))
                .stream()
                .filter(l -> getPrefix(l.getNumId(), 3).equals(parent)
                        && extractIndex(l.getNumId(), 4) >= targetIdx)
                .sorted(Comparator.comparing(l -> extractIndex(l.getNumId(), 4), Comparator.reverseOrder()))
                .collect(Collectors.toList());

        for (Level4 l : list) {
            String oldId = l.getNumId();
            int idx = extractIndex(oldId, 4);
            String newPrefix = replaceSegment(oldId, 4, idx + 1);
            level4Mapper.update(null,
                    new UpdateWrapper<Level4>().set("num_id", newPrefix).eq("id", l.getId())
            );
        }
    }

    /**
     * 更新某旧前缀下所有子级节点的新 numId
     */
    private void updateDescendants(Long stdId,String oldPrefix, String newPrefix) {
        int len = oldPrefix.length();
        level2Mapper.update(null,
                new UpdateWrapper<Level2>()
                        .eq("standard_id", stdId)
                        .setSql("num_id = CONCAT('" + newPrefix + "', SUBSTRING(num_id, " + (len+1) + "))")
                        .likeRight("num_id", oldPrefix + ".")
        );
        level3Mapper.update(null,
                new UpdateWrapper<Level3>()
                        .eq("standard_id", stdId)
                        .setSql("num_id = CONCAT('" + newPrefix + "', SUBSTRING(num_id, " + (len+1) + "))")
                        .likeRight("num_id", oldPrefix + ".")
        );
        level4Mapper.update(null,
                new UpdateWrapper<Level4>()
                        .eq("standard_id", stdId)
                        .setSql("num_id = CONCAT('" + newPrefix + "', SUBSTRING(num_id, " + (len+1) + "))")
                        .likeRight("num_id", oldPrefix + ".")
        );
    }

    /**
     * 插入后，将父节点的 if_next_level 更新为 1
     */
    private void updateParentIfNext(Long stdId,String numId) {
        String parent = numId.substring(0, numId.lastIndexOf('.'));
        int level = numId.split("\\.").length;
        switch (level) {
            case 2:
                level1Mapper.update(null,
                        new UpdateWrapper<Level1>().set("if_next_level", 1).eq("num_id", parent).eq("standard_id", stdId)
                );
                break;
            case 3:
                level2Mapper.update(null,
                        new UpdateWrapper<Level2>().set("if_next_level", 1).eq("num_id", parent).eq("standard_id", stdId)
                );
                break;
            case 4:
                level3Mapper.update(null,
                        new UpdateWrapper<Level3>().set("if_next_level", 1).eq("num_id", parent).eq("standard_id", stdId)
                );
                break;
            default:
                break;
        }
    }

    // 工具方法：解析、比较、提取编号等
    private int extractIndex(String numId, int segment) {
        return Integer.parseInt(numId.split("\\.")[segment - 1]);
    }

    private String getPrefix(String numId, int segments) {
        String[] arr = numId.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < segments; i++) {
            if (i > 0) sb.append('.');
            sb.append(arr[i]);
        }
        return sb.toString();
    }

    private String replaceSegment(String numId, int segment, int newVal) {
        String[] arr = numId.split("\\.");
        arr[segment - 1] = String.valueOf(newVal);
        return String.join(".", arr);
    }

    // DTO 转实体，实现字段映射
    private Level1 toLevel1(LevelDTO dto) {
        Level1 e = new Level1();
        e.setStandardId(dto.getStandardId());
        e.setNumId(dto.getNumId());
        e.setLevel(dto.getLevel());
        e.setName(dto.getName());
        e.setContent(dto.getContent());
        e.setImage(dto.getImageList() != null ? String.join(",", dto.getImageList()) : null);
        e.setIfNextLevel(dto.getIfNextLevel());
        return e;
    }

    private Level2 toLevel2(LevelDTO dto) {
        Level2 e = new Level2();
        e.setStandardId(dto.getStandardId());
        e.setNumId(dto.getNumId());
        e.setLevel(dto.getLevel());
        e.setName(dto.getName());
        e.setContent(dto.getContent());
        e.setImage(dto.getImageList() != null ? String.join(",", dto.getImageList()) : null);
        e.setIfNextLevel(dto.getIfNextLevel());
        return e;
    }

    private Level3 toLevel3(LevelDTO dto) {
        Level3 e = new Level3();
        e.setStandardId(dto.getStandardId());
        e.setNumId(dto.getNumId());
        e.setLevel(dto.getLevel());
        e.setName(dto.getName());
        e.setContent(dto.getContent());
        e.setImage(dto.getImageList() != null ? String.join(",", dto.getImageList()) : null);
        e.setIfNextLevel(dto.getIfNextLevel());
        return e;
    }

    private Level4 toLevel4(LevelDTO dto) {
        Level4 e = new Level4();
        e.setStandardId(dto.getStandardId());
        e.setNumId(dto.getNumId());
        e.setLevel(dto.getLevel());
        e.setName(dto.getName());
        e.setContent(dto.getContent());
        e.setImage(dto.getImageList() != null ? String.join(",", dto.getImageList()) : null);
        e.setIfNextLevel(dto.getIfNextLevel());
        return e;
    }
}
